import datetime
from flask import Flask, render_template, session, redirect, url_for
from .. import db
from ..models import User, Post, Tag, Comment
from .forms import PostForm, CommentsForm, sidebar_data, Userform
from . import post_bp
from .. auth import auth_bp

#@post_bp.route('/',methods=['GET', 'POST'])
@post_bp.route('/<int:page>')
def home(page=1):
    form = PostForm()
    posts = Post.query.order_by(Post.publish_date.desc()).paginate(page,10)
    recent, top_tags = sidebar_data()
    return render_template('post/home.html', form=form, posts=posts, recent=recent, top_tags=top_tags)

@post_bp.route('/post/<int:post_id>', methods=('GET', 'POST'))
def post(post_id):
    form = CommentsForm()
    if form.validate_on_submit():
        new_comment = Comment()
        new_comment.name = form.name.data
        new_comment.text = form.text.data
        new_comment.post_id = post_id
        new_comment.date = datetime.datetime.now()
        db.session.add(new_comment)
        db.session.commit()
    post = Post.query.get_or_404(post_id)
    tags = post.tags
    comments = post.comments.order_by(Comment.date.desc()).all()
    recent, top_tags = sidebar_data()
    return render_template('post/post.html', post=post, tags=tags, comments=comments, recent=recent, top_tags=top_tags, form=form)

@post_bp.route('/tag/<string:tag_name>')
def tag(tag_name):
    tag = Tag.query.filter_by(title=tag_name).first_or_404()
    posts = tag.posts.order_by(Post.publish_date.desc()).all()
    recent, top_tags = sidebar_data()
    return render_template('post/tag.html', tag=tag, posts=posts, recent=recent, top_tags=top_tags)

@post_bp.route('/user/<string:username>')
def user(username):
    form = Userform()
    user = User.query.filter_by(username=username).first_or_404()
    posts = user.posts.order_by(Post.publish_date.desc()).all()
    recent, top_tags = sidebar_data()
    return render_template('post/user.html',form=form, user=user, posts=posts, recent=recent, top_tags=top_tags)
